﻿//
// Created by Grishul Eugeny
//
// See license in License.txt
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.IO;
using NCommander.Core;

namespace NCommander.IconProviders
{
	internal sealed class Win32Extension : IIconProvider
	{
		public static readonly Win32Extension Instance = new Win32Extension();

		private readonly Dictionary<string, Icon> _filetypeIcon = new Dictionary<string, Icon>();

		public Win32Extension()
		{
			LoadIconsFromRegistry();
		}

		private void LoadIconsFromRegistry()
		{
			foreach( var extension in Registry.ClassesRoot.GetSubKeyNames().Where( x => x.StartsWith( "." ) ) )
			{
				using( var extensionKey = Registry.ClassesRoot.OpenSubKey( extension ) )
				{
					var description = ( string ) extensionKey.GetValue( "" );

					if( description != null )
						using( var descriptionKey = Registry.ClassesRoot.OpenSubKey( description ) )
						{
							if( descriptionKey != null)
							using( var iconKey = descriptionKey.OpenSubKey( "DefaultIcon" ) )
							{
								if( iconKey == null )
									continue;

								string iconKeyValue = ( string ) iconKey.GetValue( "" );
								if( iconKeyValue == null )
									continue;

								var iconFileDescriptor = ( iconKeyValue ).Split( ',' );

								if( iconFileDescriptor.Length < 1 || iconFileDescriptor.Length > 2 )
									continue;

								var iconHolder = iconFileDescriptor[0];
								var iconIndex = iconFileDescriptor.Length == 1 ? 0 : ( uint ) int.Parse( iconFileDescriptor[1] );

								_filetypeIcon[extension] = Win32.ExtractIcon( iconFileDescriptor[0], iconIndex );
							}
						}
				}
			}
		}

		public Icon GetIcon( string path )
		{
			var extension = Path.GetExtension( path );

			if( _filetypeIcon.ContainsKey( extension ) )
				return _filetypeIcon[extension];

			return null;
		}
	}
}
